// Copyright 2023 Innkeeper Lukexp(王晓平) &lt;37196496@qq.com>. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file. The original repo for
// this file is https://gitee.com/jetxt/jinyu.

package server

import (
	"net"
	"strconv"

	"github.com/gin-gonic/gin"
)

// 服务配置
type Config struct {
	Mode            string
	Middlewares     []string
	SecureServing   *SecureServingInfo
	InsecureServing *InsecureServingInfo
	Healthz         bool
}

// 定义安全证书
type CertKey struct {
	// CertFile is a file containing a PEM-encoded certificate, and possibly the complete certificate chain
	CertFile string
	// KeyFile is a file containing a PEM-encoded private key for the certificate specified by CertFile
	KeyFile string
}

// TSL服务配置信息，绑定地址，端口，和安全证书
type SecureServingInfo struct {
	BindAddress string
	BindPort    int
	CertKey     CertKey
}

func (s *SecureServingInfo) Address() string {
	return net.JoinHostPort(s.BindAddress, strconv.Itoa(s.BindPort))
}

// HTTP服务配置，绑定地址及端口，如 ":8080"
type InsecureServingInfo struct {
	Address string
}

// 初始化配置，即加载默认配置
func NewConfig() *Config {
	return &Config{
		Mode:        gin.DebugMode,
		Middlewares: []string{"recovery", "nocache", "cors"},
		Healthz:     true,
	}
}

// CompletedConfig 完整配置，如果有一些其他配置，可以加在这里
type CompletedConfig struct {
	*Config
}

// 补齐config,并返回完整配置
func (c *Config) Complete() *CompletedConfig {
	return &CompletedConfig{c}
}

// 完整配置的New方法，返回一个通用服务实例
func (c CompletedConfig) New() (*GenericAPIServer, error) {
	s := &GenericAPIServer{
		SecureServingInfo:   c.SecureServing,
		InsecureServingInfo: c.InsecureServing,
		mode:                c.Mode,
		middlewares:         c.Middlewares,
		Engine:              gin.New(),
		healthz:             c.Healthz,
	}

	initGenericAPIServer(s)

	return s, nil
}

// LoadConfig reads in config file and ENV variables if set.
func LoadConfig(cfg string, defaultName string) {
	//通过命令行参数指定 配置文件
	//通过Viper解析外部配置文件 .Ymal文件
}
